#include "performance.h"
#include "log.h"
#include "string.h"
#include "stdio.h"


namespace common
{

	CPerfInfo::CPerfInfo( )
	{
		total_called_ = 0;
		cost_time_ = 0;
		most_cost_time_ = 0;
		least_cost_time_ = -1;
	}

	CPerfInfo::~CPerfInfo( )
	{
	}



	/**
	 * @brief AddCalled 累加iElapsed毫秒的时间
	 *
	 * @param iElapsed 需要累加的毫秒数
	 *
	 * @return 累加的次数
	 */
	int32_t CPerfInfo::AddCalled( int32_t elapsed )
	{

		++total_called_;
		cost_time_ += elapsed;
		if ( elapsed > most_cost_time_ )
		{
			most_cost_time_ = elapsed;
		}
		if ( elapsed < least_cost_time_ || least_cost_time_ == -1 )
		{
			least_cost_time_ = elapsed;
		}
		return total_called_;
	}


	/**
	 * @brief Reset 重置统计数据
	 */
	void CPerfInfo::Reset( )
	{
		total_called_ = 0;
		cost_time_ = 0;
		most_cost_time_ = 0;
		least_cost_time_ = -1;
	}


	PerfMap CPerfStat::performance_map_;


	/**
	 * @brief LogPerfInfo 将统计信息记录到日志文件
	 *
	 * @param rPerfMap 统计信息的MAP
	 * @param pKey 要记录的文件名称
	 */
	void CPerfStat::LogPerfInfo( PerfMap& rPerfMap, const char* key )
	{
		char title[ 256 ];
		snprintf( title, sizeof( title ), "%20s\t%6s\t%6s\t%6s\t%6s\t%6s",
			"name", "called", "cost", "most", "lest", "avg" );
		LOG_INFO_C( key, "%s", title );
		auto endi = rPerfMap.end( );
		for ( auto p = rPerfMap.begin( ); p != endi; ++p )
		{
			char record[ 256 ];
			const CPerfIndex& perf_index = ( *p ).first;
			CPerfInfo& perf_info = ( *p ).second;
			sprintf( record, "%20s\t%6d\t%6d\t%6d\t%6d\t%6d",
				perf_index.name( ).c_str( ), perf_info.total_called( ),
				perf_info.cost_time( ), perf_info.most_cost_time( ), perf_info.least_cost_time( ),
				( perf_info.total_called( ) != 0 ) ? perf_info.cost_time( ) / perf_info.total_called( ) : 0 );
			LOG_INFO_C( key, "%s", record );
			perf_info.Reset( );
		}
		LOG_INFO_C( key, "\n----------------------------------------------------------------------------------" );
	}

}//namespace common
